//
//  LLNavigationBar.swift
//  LLNavigationBar
//
//  Created by 若望 on 2020/7/6.
//  Copyright © 2020 若望. All rights reserved.
//

import UIKit

public class LLNavigationBar: UINavigationBar {
    @IBInspectable var fakeView: UIVisualEffectView!
    fileprivate func setupFakeView() {
        if fakeView == nil {
            super.setBackgroundImage(UIImage(), for: .default)
            fakeView = UIVisualEffectView.init(effect: UIBlurEffect.init(style: UIBlurEffect.Style.light))
            fakeView?.isUserInteractionEnabled = false
            fakeView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            self.subviews.first?.insertSubview(fakeView, at: 0)
        }
    }
    
    @IBInspectable var backgroundImageView: UIImageView!
    fileprivate func setupBackgroundImageView() {
        if backgroundImageView == nil {
            backgroundImageView = UIImageView()
            backgroundImageView?.isUserInteractionEnabled = false
            backgroundImageView?.contentScaleFactor = 1.0
            backgroundImageView?.contentMode = .scaleToFill
            backgroundImageView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            self.subviews.first?.insertSubview(backgroundImageView, aboveSubview: self.fakeView)
        }
    }
    
    @IBInspectable var shadowImageView: UIImageView!
    fileprivate func setupShadowImageView() {
        if shadowImageView == nil {
            super.shadowImage = UIImage()
            shadowImageView = UIImageView()
            shadowImageView?.isUserInteractionEnabled = false
            shadowImageView?.contentScaleFactor = 1.0
            self.subviews.first?.insertSubview(shadowImageView, aboveSubview: self.backgroundImageView)
        }
    }
    
    
    @IBInspectable var backButtonLabel: UILabel? {
        if #available(iOS 11, *) {} else { return nil }
        if let navigationBarContentView = self.value(forKeyPath: "visualProvider.contentView") as? UIView {
            for (_, subview) in navigationBarContentView.subviews.enumerated() {
                if let cla = swiftClassFromString(className: "_UIButtonBarButton"), subview.isKind(of: cla) {
                    if let titleButton = subview.value(forKeyPath: "vvisualProvider.titleButton") as? UIButton {
                        return titleButton.titleLabel
                    }
                }
            }
        }
        return nil
    }
    
    public override func prepareForInterfaceBuilder() {
        self.setupFakeView()
        self.setupBackgroundImageView()
        self.setupShadowImageView()
    }
    
    public override init(frame: CGRect) {
        super.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44.0))
        self.setupFakeView()
        self.setupBackgroundImageView()
        self.setupShadowImageView()
    }

    public required init?(coder: NSCoder) {
        super.init(coder: coder)
        self.setupFakeView()
        self.setupBackgroundImageView()
        self.setupShadowImageView()
    }
    
    public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        if !(self.isUserInteractionEnabled) || self.isHidden || self.alpha <= 0.01 {
            return nil
        }
        if let view = super.hitTest(point, with: event) {
            let viewName = view.classForCoder.description().replacingOccurrences(of: "_", with: "")
            if view.isKind(of: self.classForCoder) {
                for (_,subview) in self.subviews.enumerated() {
                    let viewName = view.classForCoder.description().replacingOccurrences(of: "_", with: "")
                    let array = ["UINavigationItemButtonView"]
                    if array.contains(viewName) {
                        let convertedPoint: CGPoint = self.convert(point, to: subview)
                        var bounds = subview.bounds
                        if bounds.size.width < 80 {
                            bounds = bounds.insetBy(dx: bounds.size.width - 80, dy: 0)
                        }
                        if bounds.contains(convertedPoint) {
                            return view
                        }
                    }
                }
            }
            
            
            let array = ["UINavigationBarContentView", "UIButtonBarStackView", NSStringFromClass(self.classForCoder)]
            if array.contains(viewName) {
                if self.backgroundImageView.image != nil, self.backgroundImageView.alpha < 0.01 {
                    return nil
                }else if self.fakeView.alpha < 0.01 {
                    return nil
                }
            }
            if view.bounds.equalTo(CGRect.zero) {
                return nil
            }
            return view
        }
        return nil
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        if self.fakeView?.superview == nil {
            self.subviews.first?.insertSubview(fakeView, at: 0)
            self.subviews.first?.insertSubview(backgroundImageView, aboveSubview: self.fakeView)
            self.subviews.first?.insertSubview(shadowImageView, aboveSubview: self.backgroundImageView)
        }
        self.fakeView?.frame = self.fakeView?.superview?.bounds ?? CGRect.zero
        self.backgroundImageView?.frame = self.backgroundImageView?.superview?.bounds ?? CGRect.zero
        self.shadowImageView?.frame = CGRect.init(x: 0, y: (self.shadowImageView?.superview?.bounds.height ?? 0.0) - 0.5, width: self.shadowImageView?.superview?.bounds.width ?? 0.0, height: 0.5)
    }
    
    
    public override var barTintColor: UIColor? {
        didSet{
            super.barTintColor = barTintColor
            self.fakeView?.subviews.last?.backgroundColor =  barTintColor
            self.makeSureFakeView()
        }
    }
    public override func setBackgroundImage(_ backgroundImage: UIImage?, for barMetrics: UIBarMetrics) {
//        super.setBackgroundImage(backgroundImage, for: barMetrics)
        self.backgroundImageView.image = backgroundImage
        self.makeSureFakeView()
    }
    public override var isTranslucent: Bool {
        didSet {
            super.isTranslucent = true
        }
    }
    public override var shadowImage: UIImage? {
        didSet{
            self.shadowImageView.image = shadowImage
            if shadowImage != nil {
                self.shadowImageView.backgroundColor = nil
            } else {
                self.shadowImageView.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 77.0/255)
            }
            super.shadowImage = UIImage()
        }
    }

}


extension LLNavigationBar {
    fileprivate func makeSureFakeView() {
        UIView.setAnimationsEnabled(false)
        if let fakeView = self.fakeView, let fakeSuperView = fakeView.superview {
            self.subviews.first?.insertSubview(fakeView, at: 0)
            self.fakeView?.frame = fakeSuperView.bounds
        }
        if let backgroundImageView = self.backgroundImageView, let backgroundImageViewSuperView = backgroundImageView.superview {
            self.subviews.first?.insertSubview(backgroundImageView, aboveSubview: self.fakeView!)
            self.backgroundImageView?.frame = backgroundImageViewSuperView.bounds
        }
        if let shadowImageView = self.shadowImageView, let shadowImageViewSuperView = shadowImageView.superview {
            self.subviews.first?.insertSubview(shadowImageView, aboveSubview: self.backgroundImageView!)
            self.shadowImageView?.frame = CGRect.init(x: 0, y: shadowImageViewSuperView.bounds.height - 0.5, width: shadowImageViewSuperView.bounds.width, height: 0.5)
        }
        UIView.setAnimationsEnabled(true)
    }
}
/// 在swift中使用NSClassFromString className要加工程名前缀
///
/// - Parameter className: className
fileprivate func swiftClassFromString(className: String) -> AnyClass! {
    // get the project name
    if  let appName: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String? {
        // YourProject.className
        let classStringName = appName + "." + className
        return NSClassFromString(classStringName)
    }
    return nil;
}

//
//private var kFakeView: String = "kFakeView"
//private var kBackgroundImageView: String = "kBackgroundImageView"
//private var kShadowImageView: String = "kShadowImageView"
//extension UINavigationBar {
//    var fakeView: UIVisualEffectView? {
//        get {
//            return objc_getAssociatedObject(self, &kFakeView) as? UIVisualEffectView
//        }
//        set(newValue) {
//            objc_setAssociatedObject(self, &kFakeView, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
//        }
//    }
//    fileprivate func setupFakeView() {
//        if fakeView == nil {
//            self.setBackgroundImage(UIImage(), for: .default)
//            fakeView = UIVisualEffectView.init(effect: UIBlurEffect.init(style: UIBlurEffect.Style.light))
//            fakeView?.isUserInteractionEnabled = false
//            fakeView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
//            self.subviews.first?.insertSubview(fakeView!, at: 0)
//        }
//    }
//
//    var backgroundImageView: UIImageView? {
//        get {
//            return (objc_getAssociatedObject(self, &kBackgroundImageView) as? UIImageView)
//        }
//        set(newValue) {
//            objc_setAssociatedObject(self, &kBackgroundImageView, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
//        }
//    }
//    fileprivate func setupBackgroundImageView() {
//        if backgroundImageView == nil {
//            backgroundImageView = UIImageView()
//            backgroundImageView?.isUserInteractionEnabled = false
//            backgroundImageView?.contentScaleFactor = 1.0
//            backgroundImageView?.contentMode = .scaleToFill
//            backgroundImageView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
//            self.subviews.first?.insertSubview(backgroundImageView!, aboveSubview: self.fakeView!)
//        }
//    }
//
//    var shadowImageView: UIImageView? {
//        get {
//            return (objc_getAssociatedObject(self, &kShadowImageView) as? UIImageView)
//        }
//        set(newValue) {
//            objc_setAssociatedObject(self, &kShadowImageView, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
//        }
//    }
//    fileprivate func setupShadowImageView() {
//        if shadowImageView == nil {
//            self.shadowImage = UIImage()
//            shadowImageView = UIImageView()
//            shadowImageView?.isUserInteractionEnabled = false
//            shadowImageView?.contentScaleFactor = 1.0
//            self.subviews.first?.insertSubview(shadowImageView!, aboveSubview: self.backgroundImageView!)
//        }
//    }
//
//
//    @IBInspectable var backButtonLabel: UILabel? {
//        if #available(iOS 11, *) {} else { return nil }
//        if let navigationBarContentView = self.value(forKeyPath: "visualProvider.contentView") as? UIView {
//            for (_, subview) in navigationBarContentView.subviews.enumerated() {
//                if let cla = swiftClassFromString(className: "_UIButtonBarButton"), subview.isKind(of: cla) {
//                    if let titleButton = subview.value(forKeyPath: "vvisualProvider.titleButton") as? UIButton {
//                        return titleButton.titleLabel
//                    }
//                }
//            }
//        }
//        return nil
//    }
//
////    open override func prepareForInterfaceBuilder() {
////        self.setupFakeView()
////        self.setupBackgroundImageView()
////        self.setupShadowImageView()
////    }
////
////    public override convenience init(frame: CGRect) {
////        self.setupFakeView()
////        self.setupBackgroundImageView()
////        self.setupShadowImageView()
////    }
////
////    open required init?(coder: NSCoder) {
////        super.init(coder: coder)
////        self.setupFakeView()
////        self.setupBackgroundImageView()
////        self.setupShadowImageView()
////    }
//
//    open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
//        if !(self.isUserInteractionEnabled) || self.isHidden || self.alpha <= 0.01 {
//            return nil
//        }
//        if let view = super.hitTest(point, with: event) {
//            let viewName = view.classForCoder.description().replacingOccurrences(of: "_", with: "")
//            if view.isKind(of: self.classForCoder) {
//                for (_,subview) in self.subviews.enumerated() {
//                    let viewName = view.classForCoder.description().replacingOccurrences(of: "_", with: "")
//                    let array = ["UINavigationItemButtonView"]
//                    if array.contains(viewName) {
//                        let convertedPoint: CGPoint = self.convert(point, to: subview)
//                        var bounds = subview.bounds
//                        if bounds.size.width < 80 {
//                            bounds = bounds.insetBy(dx: bounds.size.width - 80, dy: 0)
//                        }
//                        if bounds.contains(convertedPoint) {
//                            return view
//                        }
//                    }
//                }
//            }
//
//
//            let array = ["UINavigationBarContentView", "UIButtonBarStackView", NSStringFromClass(self.classForCoder)]
//            if array.contains(viewName) {
//                if self.backgroundImageView?.image != nil, (self.backgroundImageView?.alpha ?? 1.0) < 0.01 {
//                    return nil
//                }else if (self.fakeView?.alpha ?? 1.0) < 0.01 {
//                    return nil
//                }
//            }
//            if view.bounds.equalTo(CGRect.zero) {
//                return nil
//            }
//            return view
//        }
//        return nil
//    }
//
//    open override func setNeedsLayout() {
//       super.layoutSubviews()
//    }
//
//    open override func layoutIfNeeded() {
//        super.layoutIfNeeded()
//    }
//
//    open override func layoutSubviews() {
//        super.layoutSubviews()
//        self.setupFakeView()
//        self.setupBackgroundImageView()
//        self.setupShadowImageView()
//        self.setupBarTintColor()
//        self.setupBackgroundImage()
//        self.setupShadowImage()
//
//        if self.fakeView?.superview == nil {
//            self.subviews.first?.insertSubview(fakeView!, at: 0)
//            self.subviews.first?.insertSubview(backgroundImageView!, aboveSubview: self.fakeView!)
//            self.subviews.first?.insertSubview(shadowImageView!, aboveSubview: self.backgroundImageView!)
//        }
//        self.fakeView?.frame = self.fakeView?.superview?.bounds ?? CGRect.zero
//        self.backgroundImageView?.frame = self.backgroundImageView?.superview?.bounds ?? CGRect.zero
//        self.shadowImageView?.frame = CGRect.init(x: 0, y: (self.shadowImageView?.superview?.bounds.height ?? 0.0) - 0.5, width: self.shadowImageView?.superview?.bounds.width ?? 0.0, height: 0.5)
//    }
//
//    fileprivate func setupBarTintColor() {
//        self.fakeView?.subviews.last?.backgroundColor =  barTintColor
//        self.makeSureFakeView()
//    }
//
//    fileprivate func setupBackgroundImage() {
//        self.backgroundImageView?.image = self.backgroundImage(for: UIBarMetrics.default)
//        self.makeSureFakeView()
//    }
//
//    fileprivate func setupShadowImage() {
//        self.shadowImageView?.image = shadowImage
//        if shadowImage != nil {
//            self.shadowImageView?.backgroundColor = nil
//        } else {
//            self.shadowImageView?.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 77.0/255)
//        }
//    }
//
//    fileprivate func makeSureFakeView() {
//        UIView.setAnimationsEnabled(false)
//        if let fakeView = self.fakeView, let fakeSuperView = fakeView.superview {
//            self.subviews.first?.insertSubview(fakeView, at: 0)
//            self.fakeView?.frame = fakeSuperView.bounds
//        }
//        if let backgroundImageView = self.backgroundImageView, let backgroundImageViewSuperView = backgroundImageView.superview {
//            self.subviews.first?.insertSubview(backgroundImageView, aboveSubview: self.fakeView!)
//            self.backgroundImageView?.frame = backgroundImageViewSuperView.bounds
//        }
//        if let shadowImageView = self.shadowImageView, let shadowImageViewSuperView = shadowImageView.superview {
//            self.subviews.first?.insertSubview(shadowImageView, aboveSubview: self.backgroundImageView!)
//            self.shadowImageView?.frame = CGRect.init(x: 0, y: shadowImageViewSuperView.bounds.height - 0.5, width: shadowImageViewSuperView.bounds.width, height: 0.5)
//        }
//        UIView.setAnimationsEnabled(true)
//    }
//}
